package com.hos.db.manager;


import com.hos.db.create.user.UserDocTable;
import com.hos.db.create.user.UserPatTable;
import com.hos.db.create.visit.VisitTable;
import com.hos.db.entity.visit.VisitEntity;
import com.hos.db.entity.visit.VisitEntityDoc;
import com.hos.db.entity.visit.VisitEntityPat;
import com.hos.net.req.visit.VisitAddReq;
import com.hos.net.req.visit.VisitDeleteReq;
import com.hos.net.req.visit.VisitMsgReq;
import com.hos.net.req.visit.VisitUpdateReq;
import com.hos.net.res.BaseResponse;
import com.hos.net.res.MsgHint;
import com.hos.utile.DLog;
import com.hos.utile.DateUtile;
import com.hos.utile.Md5Utile;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//随访
public class VisitsManager {

    private static VisitsManager userPatsManager;

    public static VisitsManager getInstance() {
        if (userPatsManager == null) {
            userPatsManager = new VisitsManager();
        }
        return userPatsManager;
    }

    /**
     * 添加随访
     *
     * @param jdbcTemplate
     * @param req
     * @return
     */
    public String onVisitAddReq(JdbcTemplate jdbcTemplate, String docId,
                                VisitAddReq req) {

        String response = new MsgHint("添加失败").toJson();

        String sql = "INSERT INTO " + VisitTable.tableName
                + "("
                + VisitTable.tableVisitId + ","
                + VisitTable.tablePatId + ","
                + VisitTable.tableDocId + ","
                + VisitTable.tableVisitMsg + ","
                + VisitTable.tableVisitState + ","
                + VisitTable.tableVisitInspectTime + ","
                + VisitTable.tableVisitReviewTime + ","
                + VisitTable.tableVisitCreateTime + ","
                + VisitTable.tableVisitUpdateTime
                + ")"
                + " VALUES (?,?, ?, ?,?, ?, ?, ?,?)";

        try {
            Date time = new Date();
            String t = DateUtile.getDateFormat(time, DateUtile.DATA_FORMAT_YMD_HMS);
            String visitId = Md5Utile.encode(docId + t);
            int status = jdbcTemplate.update(sql,
                    new Object[]{visitId, req.patId, docId, req.msg,
                            0, req.visitInspectTime, req.visitReviewTime, time, time});
            if (status > 0) {
                VisitEntity visitEntity = new VisitEntity();
                visitEntity.setVisitId(visitId);
                visitEntity.setDocId(docId);
                visitEntity.setPatId(req.patId);
                visitEntity.setVisitMsg(req.msg);
                visitEntity.setVisitInspectTime(req.visitInspectTime);
                visitEntity.setVisitReviewTime(req.visitReviewTime);
                visitEntity.setVisitCreateTime(time);
                visitEntity.setVisitUpdateTime(time);
                visitEntity.setVisitState(0);
                //
                BaseResponse res = new BaseResponse();
                res.obj = visitEntity;
                response = res.toJson("0", "添加成功");
            }
        } catch (Exception e) {
            DLog.e("添加失败：" + e.getMessage());
        }
        return response;
    }

    /**
     * 修改访问
     *
     * @param jdbcTemplate
     * @param req
     * @return
     */
    public String onVisitUpdateReq(JdbcTemplate jdbcTemplate, VisitUpdateReq req) {

        String response = new MsgHint("修改失败").toJson();
        String update = "";
        String msg = req.msg;
        if (msg != null && msg != "") {
            update += " , " + VisitTable.tableVisitMsg + " = '" + msg + "'";
        }
        Date visitInspectTime = req.visitInspectTime;
        if (visitInspectTime != null) {
            update += " , " + VisitTable.tableVisitInspectTime + " = '"
                    + DateUtile.getDateFormat(visitInspectTime, DateUtile.DATA_FORMAT_YMD_HMS) + "'";
        }
        Date visitReviewTime = req.visitReviewTime;
        if (visitInspectTime != null) {
            update += " , " + VisitTable.tableVisitReviewTime + " = '"
                    + DateUtile.getDateFormat(visitReviewTime, DateUtile.DATA_FORMAT_YMD_HMS) + "'";
        }
        if (update.equals("")) {
            return new MsgHint("请设置要修改的参数").toJson();
        }
        //
        Date time = new Date();
        String t = DateUtile.getDateFormat(time, DateUtile.DATA_FORMAT_YMD_HMS);
        //
        update += " , " + VisitTable.tableVisitUpdateTime + " = '" + t + "'";
        update = update.replaceFirst(" , ", "");
        String sql = "UPDATE " + VisitTable.tableName
                + " SET "
                + update
                + " WHERE "
                + VisitTable.tableVisitId + " = '" + req.visitId + "'";
        try {
            int status = jdbcTemplate.update(sql);
            if (status > 0) {
                response = new MsgHint("0", "修改成功").toJson();
            }
        } catch (Exception e) {
            DLog.e("修改失败：" + e.getMessage());
        }
        return response;
    }

    //修改访问信息
    public String onVisitMsgReq(JdbcTemplate jdbcTemplate, VisitMsgReq req) {
        String sql = "UPDATE " + VisitTable.tableName
                + " SET "
                + VisitTable.tableVisitMsg + " = '" + req.visitMsg + "' , "
                + VisitTable.tableVisitUpdateTime + " = '"
                + DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS) + "'"
                + " WHERE "
                + VisitTable.tableVisitId + " = '" + req.visitId + "'";
        int state = jdbcTemplate.update(sql);
        if (state == 0) {
            return new MsgHint("修改失败").toJson();
        }
        return new MsgHint("0", "修改成功").toJson();

    }

    //删除访问
    public String onVisitDeleteReq(JdbcTemplate jdbcTemplate, VisitDeleteReq req) {
        String sql = "DELETE  FROM " + VisitTable.tableName
                + " WHERE "
                + VisitTable.tableVisitId + " = '" + req.visitId + "'";
        int state = jdbcTemplate.update(sql);
        if (state == 0) {
            return new MsgHint("删除失败").toJson();
        }
        return new MsgHint("0", "删除成功").toJson();

    }

    /**
     * 获取访问列表 na 更新时间排序
     *
     * @param jdbcTemplate
     * @param patId        患者id
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     * @param hasNextPage  判断是否有下一页
     */
    public List<VisitEntity> onVisitsReq(JdbcTemplate jdbcTemplate, String docId,
                                         String patId, int pageNo, int pageSize,
                                         boolean hasNextPage) {
        //SELECT column_name,column_name FROM table_name [WHERE Clause] [LIMIT N][ OFFSET M]
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String w = "";
        String and = " WHERE ";
        if (patId != null && patId != "") {
            w = " WHERE "
                    + VisitTable.tablePatId + " = '" + patId + "'";
            and = " AND ";
        }

        if (docId != null && docId != "") {
            w += and
                    + VisitTable.tableDocId + " = '" + docId + "'";
        }

        String sql = "SELECT * FROM " + VisitTable.tableName
                + w
                + " ORDER BY " + VisitTable.tableVisitUpdateTime
                + " DESC "
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);

        List<VisitEntity> list = onQuery(jdbcTemplate, sql);
        if (list == null) {
            list = new ArrayList();
        }
        return list;
    }

    /**
     * 医生获取随访
     *
     * @param jdbcTemplate
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     * @param isComplete   true 已经完成的 falae 未完成的
     */
    public List<VisitEntityPat> onPatVisitsReq(JdbcTemplate jdbcTemplate, String docId, boolean isComplete,
                                               int pageNo, int pageSize, boolean hasNextPage) {
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String and = "";
        String order = "";
        if (isComplete) {
            //已经完成的
            and = VisitTable.tableVisitReviewTime + " < '" + DateUtile.getDateFormat(new Date(),
                    DateUtile.DATA_FORMAT_YMD) + "' ";
            //降序
            order = " DESC ";
        } else {
            //未完成的
            and = VisitTable.tableVisitReviewTime + " >= '" + DateUtile.getDateFormat(new Date(),
                    DateUtile.DATA_FORMAT_YMD) + "' ";
            //升序
            order = " asc ";
        }

        String sql = "SELECT "
                + "r." + VisitTable.tableVisitId
                + " ,r." + VisitTable.tablePatId
                + " ,r." + VisitTable.tableDocId
                + " ,r." + VisitTable.tableVisitMsg
                + " ,r." + VisitTable.tableVisitState
                + " ,r." + VisitTable.tableVisitInspectTime
                + " ,r." + VisitTable.tableVisitReviewTime
                + " ,r." + VisitTable.tableVisitCreateTime
                + " ,r." + VisitTable.tableVisitUpdateTime
                //
                + " ,d." + UserPatTable.tablePatName
                + " ,d." + UserPatTable.tablePatPortrait
                + " ,d." + UserPatTable.tablePatIdentityNumber
                //
                + " from "
                + VisitTable.tableName + " r "
                + " LEFT OUTER JOIN  "
                + UserPatTable.tableName + " d "
                + " on "
                + "r." + VisitTable.tablePatId
                + " = "
                + "d." + UserPatTable.tablePatId
                + " WHERE "
                + "r." + VisitTable.tableDocId + " = '" + docId + "'"
                + " AND "
                + and
                + " ORDER BY " + VisitTable.tableVisitReviewTime
                + order
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        List<VisitEntityPat> visits = jdbcTemplate.query(sql,
                ParameterizedBeanPropertyRowMapper.newInstance(VisitEntityPat.class));
        return visits;
    }
    /**
     * 患者获取随访
     *
     * @param jdbcTemplate
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     * @param isComplete   true 已经完成的 falae 未完成的
     */
    public List<VisitEntityDoc> onDocVisitsReq(JdbcTemplate jdbcTemplate, String patId, boolean isComplete,
                                               int pageNo, int pageSize, boolean hasNextPage) {
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String and = "";
        String order = "";
        if (isComplete) {
            //已经完成的
            and = VisitTable.tableVisitReviewTime + " < '" + DateUtile.getDateFormat(new Date(),
                    DateUtile.DATA_FORMAT_YMD) + "' ";
            //降序
            order = " DESC ";
        } else {
            //未完成的
            and = VisitTable.tableVisitReviewTime + " >= '" + DateUtile.getDateFormat(new Date(),
                    DateUtile.DATA_FORMAT_YMD) + "' ";
            //升序
            order = " asc ";
        }

        String sql = "SELECT "
                + "r." + VisitTable.tableVisitId
                + " ,r." + VisitTable.tablePatId
                + " ,r." + VisitTable.tableDocId
                + " ,r." + VisitTable.tableVisitMsg
                + " ,r." + VisitTable.tableVisitState
                + " ,r." + VisitTable.tableVisitInspectTime
                + " ,r." + VisitTable.tableVisitReviewTime
                + " ,r." + VisitTable.tableVisitCreateTime
                + " ,r." + VisitTable.tableVisitUpdateTime
                //
                + " ,d." + UserDocTable.tableDocName
                + " ,d." + UserDocTable.tableDocPortrait
                + " ,d." + UserDocTable.tableDocIdentityNumber
                //
                + " from "
                + VisitTable.tableName + " r "
                + " LEFT OUTER JOIN  "
                + UserDocTable.tableName + " d "
                + " on "
                + "r." + VisitTable.tableDocId
                + " = "
                + "d." + UserDocTable.tableDocId
                + " WHERE "
                + "r." + VisitTable.tablePatId  + " = '" + patId + "'"
                + " AND "
                + and
                + " ORDER BY " + VisitTable.tableVisitReviewTime
                + order
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        List<VisitEntityDoc> visits = jdbcTemplate.query(sql,
                ParameterizedBeanPropertyRowMapper.newInstance(VisitEntityDoc.class));
        return visits;
    }
    //查询访问
    private List<VisitEntity> onQuery(JdbcTemplate jdbcTemplate, String sql) {
        List<VisitEntity> list = null;
        try {
            list = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(VisitEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return list;
    }
}
